package com.lzj.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2021/12/13
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取资源请求路径
        String uri = request.getRequestURI();

        //判断是否包含登录相关资源路径,要注意排除掉css,js,验证码等资源
        if (uri.contains("/login.jsp") || uri.contains("/Login") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/index.jsp") || uri.contains("/images/") || uri.contains("/register.jsp")||uri.contains("/Register")) {

            //包含放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {

            //不包含,跳转登陆页面
            //从session中获取user
            Object user = request.getSession().getAttribute("userId");
            if (user != null) {

                //登录了放行
                filterChain.doFilter(servletRequest, servletResponse);
            } else {

                //没有登陆，跳转登陆页面
                request.setAttribute("msg", "您尚未登录，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request, servletResponse);
            }
        }
    }
}
